import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken,getUser,isTokenExpired } from '@/utils/auth'
NProgress.configure({
  showSpinner: false
})

const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  NProgress.start()
  var token=getToken()
  if (!isTokenExpired(token)) {
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      var user = getUser()
      if (!user) {
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(() => {
          user = getUser()
          getRoutes(to,next,user.permissions)
          next()
        }).catch(err => {
          store.dispatch('LogOut').then(() => {
            Message.error(err != undefined ? err : '登录失败')
            next({ path: '/' })
          })
        })
      } else {
        if(store.getters.sidebarRouters.length===0){
          getRoutes(to,next,user.permissions)
        }
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
function getRoutes(to,next,userPermissions){
  store.dispatch('GenerateRoutes',userPermissions).then(accessRoutes => {
    router.addRoutes(accessRoutes) // 动态添加可访问路由表
    next({ ...to, replace: true })// hack方法 确保addRoutes已完成
  })
}